"""
采集内存信息
"""
from ResponseData import ResponseData
from lib.plugins.BasePlugin import BasePlugin
from lib.utils import convert


class MemoryPlugin(BasePlugin):
    def process(self, ssh_func, hostname):
        res = ResponseData()
        try:
            cmd = 'dmidecode -q -t 17 2>/dev/null'
            output = ssh_func(hostname, cmd)
            res.data = self.parse(output)
        except Exception as e:
            res.status = 500
            res.msg = "error"
        return res.__dict__

    def parse(self, content):
        ram_dict = {}
        key_map = {
            'Size': 'capacity',
            'Locator': 'slot',
            'Type': 'model',
            'Speed': 'speed',
            'Manufacturer': 'manufacturer',
            'Serial Number': 'sn'
        }
        devices = content.split('Memory Device')
        for item in devices:
            row_data = item.strip()
            if not item:
                continue
            if item.startswith('#'):
                continue
            segment = {}
            lines = item.split('\n\t')
            for line in lines:
                if len(line.split(':')) > 1:
                    key, value = line.split(':')
                else:
                    key = line.split(':')[0]
                    value = ""
                if key in key_map:
                    if key == 'Size':
                        segment[key_map['Size']] = convert.convert_mb_to_gb(value, 0)
                    else:
                        segment[key_map[key.strip()]] = value.strip()
            ram_dict[segment['slot']] = segment
        return ram_dict
